/**
 * Copyright 2016 JustWayward Team
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.songcha.module_bookreader.ui.view.readview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Region;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.util.Log;
import android.view.View;

import com.songcha.library_common.util.LogUtil;
import com.songcha.module_bookreader.manager.SettingManager;
import com.songcha.module_bookreader.manager.ThemeManager;
import com.songcha.module_bookreader.utils.LogUtils;


public class OverlappedReadWidget extends BaseReadView {

    private Path mPath0;

    GradientDrawable mBackShadowDrawableLR;
    GradientDrawable mBackShadowDrawableRL;

    private Path mXORPath=new Path();

    private FlipDirection mFlipDirection=FlipDirection.NONE;

    public OverlappedReadWidget(Context context, int width, int height, String bookId,
                                IOnReadStateChangeListener listener, boolean isOnDrawWord, String fontPath,
                                boolean isFromSD,boolean isChapterLastAdvertPreLoadEnabled,
                                IOnChapterAdvertListener chapterAdvertListener) {
        super(context, width,height,bookId, listener,isOnDrawWord,fontPath,isFromSD,isChapterLastAdvertPreLoadEnabled, chapterAdvertListener);

        mTouch.x = 0.01f;
        mTouch.y = 0.01f;

        mPath0 = new Path();

        int[] mBackShadowColors = new int[]{0xaa666666, 0x666666};
        mBackShadowDrawableRL = new GradientDrawable(GradientDrawable.Orientation.RIGHT_LEFT, mBackShadowColors);
        mBackShadowDrawableRL.setGradientType(GradientDrawable.LINEAR_GRADIENT);

        mBackShadowDrawableLR = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, mBackShadowColors);
        mBackShadowDrawableLR.setGradientType(GradientDrawable.LINEAR_GRADIENT);
    }

    @Override
    protected void drawCurrentPageArea(Canvas canvas) {
        mPath0.reset();

        canvas.save();
        if (mFlipDirection==FlipDirection.RIGHT) {
            mPath0.moveTo(mCanvasWidth + mTouchDeltaX, 0);
            mPath0.lineTo(mCanvasWidth + mTouchDeltaX, mCanvasHeight);
            mPath0.lineTo(mCanvasWidth, mCanvasHeight);
            mPath0.lineTo(mCanvasWidth, 0);
            mPath0.lineTo(mCanvasWidth + mTouchDeltaX, 0);
            mPath0.close();
            clipPathXor(canvas);
            canvas.drawBitmap(mCurPageBitmap, mTouchDeltaX, 0, null);
          /*  Rect srcRect=new Rect((int)mTouchDelta*-1,0,mCanvasWidth,mCanvasHeight);
            Rect dstRect=new Rect(0,0,mCanvasWidth+(int)mTouchDelta,mCanvasHeight);
            canvas.drawBitmap(mCurPageBitmap,srcRect,dstRect,null);*/
        } else {
            mPath0.moveTo(mTouchDeltaX, 0);
            mPath0.lineTo(mTouchDeltaX, mCanvasHeight);
            mPath0.lineTo(mCanvasWidth, mCanvasHeight);
            mPath0.lineTo(mCanvasWidth, 0);
            mPath0.lineTo(mTouchDeltaX, 0);
            mPath0.close();
            canvas.clipPath(mPath0);
            canvas.drawBitmap(mCurPageBitmap, mTouchDeltaX, 0, null);
        }
        try {
            canvas.restore();
        } catch (Exception e) {

        }
    }

    @Override
    protected void drawCurrentPageShadow(Canvas canvas) {
        /*canvas.save();
        GradientDrawable shadow;
        if (mFlipDirection==FlipDirection.RIGHT) {
            shadow = mBackShadowDrawableLR;
            shadow.setBounds((int) (mCanvasWidth + mTouchDelta - 5), 0, (int) (mCanvasWidth + mTouchDelta + 5), mCanvasHeight);

        } else {
            shadow = mBackShadowDrawableRL;
            shadow.setBounds((int) (mTouchDelta - 5), 0, (int) (mTouchDelta + 5), mCanvasHeight);
        }
        shadow.draw(canvas);
        try {
            canvas.restore();
        } catch (Exception e) {

        }*/
    }

    @Override
    protected void drawCurrentBackArea(Canvas canvas) {
        // do nothing
    }

    @Override
    protected void drawNextPageAreaAndShadow(Canvas canvas) {
        canvas.save();
        if (mFlipDirection == FlipDirection.RIGHT) {
            canvas.clipPath(mPath0);
            canvas.drawBitmap(mNextPageBitmap, 0, 0, null);
        } else {
            //canvas.clipPath(mPath0, Region.Op.XOR);
            clipPathXor(canvas);
            canvas.drawBitmap(mNextPageBitmap, 0, 0, null);
        }
        try {
            canvas.restore();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void clipPathXor(Canvas canvas){
        if (Build.VERSION.SDK_INT >= 28) {
            mXORPath.reset();
            mXORPath.moveTo(0f, 0f);
            mXORPath.lineTo(canvas.getWidth(), 0f);
            mXORPath.lineTo(canvas.getWidth(), canvas.getHeight());
            mXORPath.lineTo(0f, canvas.getHeight());
            mXORPath.close();
            // 取 path 的补集，作为 canvas 的交集
            mXORPath.op(mPath0, Path.Op.XOR);
            canvas.clipPath(mXORPath);
            //canvas.clipPath(mPath0, Region.Op.XOR);
        }else{
            canvas.clipPath(mPath0, Region.Op.XOR);
        }

    }

    @Override
    protected void calcPoints() {

    }

    @Override
    protected void calcCornerXY(float x, float y,FlipDirection direction) {

    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            float x = mScroller.getCurrX();
            float y = mScroller.getCurrY();
            if (mFlipDirection == FlipDirection.RIGHT) {
                mTouchDeltaX = -(mCanvasWidth - x);
            } else {
                mTouchDeltaX = x;
            }
            mTouch.y = y;
            //mTouchDelta = mTouch.x - mLastX;
            postInvalidate();
        }else{
            //mTouchDeltaX = 0;
        }
        super.computeScroll();
    }

    @Override
    protected void startAnimation(FlipDirection direction) {
        int dx;
        mFlipDirection=direction;
        if (mFlipDirection==FlipDirection.RIGHT) {
            dx = (int) -(mCanvasWidth + mTouchDeltaX);
            mScroller.startScroll((int) (mCanvasWidth + mTouchDeltaX), (int) mTouch.y, dx, 0, START_ANIMATION_TIME);
        } else {
            dx = (int) (mCanvasWidth - mTouchDeltaX);
            mScroller.startScroll((int) mTouchDeltaX, (int) mTouch.y, dx, 0, START_ANIMATION_TIME);
        }
    }

    @Override
    protected void abortAnimation() {
        if (!mScroller.isFinished()) {
            mScroller.abortAnimation();
        }
    }

    @Override
    protected void onAnimationUpdate(FlipDirection direction) {
        mFlipDirection=direction;
    }

    @Override
    protected void restoreAnimation(FlipDirection direction) {
        int startX;
        int dx;
        mFlipDirection = direction;
        if (isRight()) {
            startX = (int)(mCanvasWidth + mTouchDeltaX);
            dx = (int)-mTouchDeltaX;
        } else {
            startX = (int)mTouchDeltaX;
            dx = (int)-mTouchDeltaX;
        }
        mScroller.startScroll(startX, (int)mTouch.y, dx, 0, CANCEL_ANIMATION_TIME);
    }

    private boolean isRight(){
        return mFlipDirection == FlipDirection.RIGHT;
    }

    public void setBitmaps(Bitmap bm1, Bitmap bm2) {
        mCurPageBitmap = bm1;
        mNextPageBitmap = bm2;
    }

    @Override
    protected void drawChapterLastAdvertViewAnimation(Canvas canvas,View adView) {
        startChapterLastAdvertViewAnim(adView,mTouchDeltaX);
    }

    private void startChapterLastAdvertViewAnim(View adView,float deltaX){
        //if(deltaX == 0f) return;
        //LogUtils.d("aaa",deltaX);
        //TODO
        LayoutParams lp = (LayoutParams) adView.getLayoutParams();
        lp.leftMargin = (int)(deltaX);
        lp.rightMargin = (int)(-deltaX);
        adView.setLayoutParams(lp);
    }

    @Override
    public synchronized void setTheme(int theme) {
        resetTouchPoint();
        Bitmap bg = ThemeManager.getThemeDrawable(theme);
        super.setBackgroundBitmap(bg);
    }

    @Override
    public void setBackgroundBitmap(Bitmap bitmap) {
        resetTouchPoint();
        super.setBackgroundBitmap(bitmap);
    }
}
